package com.cafuc.base;

import com.cafuc.entity.User;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectOperation {
    public void reflectTest() throws Exception {
        //类模板
        Class class1 = User.class;
        Class class2 =Class.forName("com.cafuc.entity.User");
        User user = new User();
        Class class3 = user.getClass();
        System.out.println(class1 == class2);
        System.out.println(class2 == class3);
        System.out.println(class1.getName() + "-"
                + class1.getPackage().getName() + "-"
                + class1.getSuperclass().getName() + "-"
                + class1.isInterface());

        //构造器的操作
        User user1 = (User) class1.newInstance();
        System.out.println(user1.getName());
        Constructor<User> con1= class1.getDeclaredConstructor(null);
        User user2 = con1.newInstance();
        System.out.println(user2.getName());
        Constructor<User> con2 = class1.getDeclaredConstructor(
                new Class[] {int.class, String.class, int.class});
        User user3 = con2.newInstance(new Object[] {1, "daxunhua", 20});
        System.out.println(user3.getName());

        //属性的操作
        Field field = class1.getDeclaredField("name");
        field.setAccessible(true);
        field.set(user1, "daxunhua");
        System.out.println(user1.getName());

        //方法的操作
        Method method = class1.getDeclaredMethod("call", null);
        method.setAccessible(true);
        method.invoke(user1, null);


    }
    public static void main(String[] args) throws Exception {
        ReflectOperation ro = new ReflectOperation();
        ro.reflectTest();
    }
}
